<template>
    <div>
    <div class="form">
        <el-form :inline="true" :model="searchData" class="demo-form-inline">
            <el-form-item>
                <el-input class="input" v-model="searchData.spuName" placeholder="请输入商品名称" clearable />
            </el-form-item>
            <el-form-item>
                <el-input class="input" v-model="searchData.id" placeholder="请输入团购ID" clearable />
            </el-form-item>
            <el-form-item>
                <el-select v-model="searchData.status" class="m-2" placeholder="请选择活动状态" size="large" clearable>
                    <el-option v-for="item in adStatusMap" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handelSearch">查找</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Plus" @click="handelAdd">添加</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div>
        <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column type="expand">
                <template #default="props">
                    <div>
                        <el-descriptions title=" " border :column="1">
                            <el-descriptions-item label="类目ID" width="120px">
                                {{ props.row.categoryId }}
                            </el-descriptions-item>
                            <el-descriptions-item label="商品sku属性" width="120px">
                                <el-table :data="props.row.groupShopSkuDTOList" style="width: 100%" border
                                    :header-cell-style="{ 'text-align': 'center' }"
                                    :cell-style="{ 'text-align': 'center' }">
                                    <el-table-column prop="skuId" label="SkuId" width="180" />
                                    <el-table-column prop="title" label="规格标题" width="180" />
                                    <el-table-column prop="skuGroupShopPrice" label="团购价格(元)" />
                                    <el-table-column prop="stock" label="库存" />
                                    <el-table-column prop="originalPrice" label="原始价格(元)" />
                                    <el-table-column prop="price" label="售卖价格(元)" />
                                    <el-table-column prop="vipPrice" label="会员价格(元)" />
                                    <el-table-column prop="barCode" label="国际条码" />
                                </el-table>
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="团购ID" prop="id" />
            <el-table-column label="商品ID" prop="spuId" width="100" />
            <el-table-column label="商品名称" prop="title" width="180" />
            <el-table-column label="商品主图">
                <template #default="scope">
                    <el-popover effect="light" trigger="hover" placement="right" width="auto">
                        <template #default>
                            <img :src="scope.row.img" alt="" width="300">
                        </template>
                        <template #reference>
                            <img :src="scope.row.img" alt="" width="50">
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="未满策略">
                <template #default="scope">
                    <el-tag :type="scope.row.automaticRefund == 0 ? 'success' : 'warning'">
                        {{ scope.row.automaticRefund == 0 ? '退款' : '发货' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="活动状态">
                <template #default="scope">
                    <el-tag :type="scope.row.status == 0 ? 'danger' : ''">
                        {{ scope.row.status == 0 ? '冻结' : '活动' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="开始时间" width="180">
                <template #default="scope">
                    {{ new Date(scope.row.gmtStart).friendTime(2) }}
                </template>
            </el-table-column>
            <el-table-column label="结束时间" width="180">
                <template #default="scope">
                    {{ new Date(scope.row.gmtEnd).friendTime(2) }}
                </template>
            </el-table-column>
            <el-table-column label="当前人数" prop="sales" />
            <el-table-column label="目标人数" prop="minNum" />
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button v-show="scope.row.status==0" size="small" type="primary" @click="handelEdit(scope.row)">编辑</el-button>
                    <el-button v-show="scope.row.status==0" size="small" type="danger" @click="handelDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div>
        <Pagetion v-bind="pagetio" @page-change="pageChange"></Pagetion>
    </div>
    <div>
        <el-backtop target=".el-main" :right="100" :bottom="100" ref="backTop" :visibility-height="20" />
    </div>

    <div>
        <el-drawer v-model="drawer" direction="ltr" size="50%" :show-close="false" destroy-on-close>
            <template #header>
                <div>
                    <span>{{ tit }}团购商品</span>
                </div>
                <el-button>取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">{{ tit == '创建' ? '创建' : '更新' }}</el-button>
            </template>
            <template #default>
                <div class="drawer_spu">
                    <h4>商品属性(spu)</h4>
                    <div class="drawer_spu_item">
                        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-position="left"
                            label-width="150px" class="demo-ruleForm">
                            <el-form-item label="团购商品" prop="spuId">
                                <el-cascader :options="productData" v-model="ruleForm.spuId" placeholder="请选择商品"
                                    clearable @change="loadDrawSkuList"
                                    :props="{ checkStrictly: false, children: 'children', value: 'id', label: 'label', emitPath: false }" />
                            </el-form-item>
                            <el-form-item label="团购时间" prop="gmtEnd">
                                <el-date-picker v-model="ruleForm.gmtStart" type="datetime" placeholder="请选择时间日期"
                                    format="YYYY/MM/DD hh:mm:ss" value-format="x" />
                                <span style="margin: 0 5px;">至</span>
                                <el-date-picker v-model="ruleForm.gmtEnd" type="datetime" placeholder="请选择时间日期"
                                    format="YYYY/MM/DD hh:mm:ss" value-format="x" />
                            </el-form-item>
                            <el-form-item label="团购基础人数" prop="age">
                                <el-input-number v-model="ruleForm.minNum" :min="1" :max="10" controls-position="right"
                                    size="large" />
                            </el-form-item>
                            <el-form-item label="团购结束时人数没有" prop="age">
                                <el-radio-group v-model="ruleForm.automaticRefund" size="large">
                                    <el-radio-button :label="0">不退款 我要发货</el-radio-button>
                                    <el-radio-button :label="1">自动退款 我要发货</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="达到基础人数时采取:">
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <div class="drawer_sku">
                    <div class="drawer_sku_header">
                        <h4>商品类型(sku)</h4>
                        <el-popover v-model:visible="hidePopover" placement="right" :width="400" trigger="click"
                            destroy-on-close>
                            <p class="popover_p">
                                <el-form label-width="103" label-position="left">
                                    <el-form-item label="团购价格">
                                        <el-input-number v-model="batchPrice" :min="1" controls-position="right"
                                            size="large" :precision="2" />元
                                    </el-form-item>
                                </el-form>
                            </p>
                            <div style="text-align: center; margin: 10px 0;">
                                <el-button size="small" @click="hidePopover = false">取消</el-button>
                                <el-button size="small" type="primary" @click="handelGroupPrice">确定</el-button>
                            </div>
                            <template #reference>
                                <el-button type="primary" plain :disabled="drawerSkuList.length == 0">批量定价</el-button>
                            </template>
                        </el-popover>
                    </div>
                    <div>
                        <el-table :data="drawerSkuList" style="width: 100%"
                            :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                            <el-table-column prop="id" label="SkuId" />
                            <el-table-column prop="barCode" label="Sku条形码" />
                            <el-table-column prop="title" label="类型名" />
                            <el-table-column prop="stock" label="库存" />
                            <el-table-column prop="price" label="现价/元" />
                            <el-table-column prop="skuGroupShopPrice" label="团购价格/元" />
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <el-button size="small" type="primary"
                                        @click="handelUpdate(scope.$index, scope.row)">更新</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </template>
        </el-drawer>
        <!-- skuList更新弹窗 -->
        <div>
            <el-dialog v-model="dialogVisible" title="更新团购价格" width="30%" destroy-on-close>
                <div>
                    <el-form label-width="103" label-position="left">
                        <el-form-item label="团购价格">
                            <el-input-number v-model="updateGroupPrice" :min="1" controls-position="right"
                                size="large" :precision="2"/>
                        </el-form-item>
                        <el-form-item label="现价">
                            {{ updateData.price }}
                        </el-form-item>
                        <el-form-item label="sku类名">
                            {{ updateData.title }}
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirmUpdate">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { post } from '@/http/request';
import { Search, Plus, } from '@element-plus/icons-vue'
import { ClassPagination, ClassGroupEdit } from "#/index";
import "@/utils/DateFormatter";//友好日期
import Pagetion from "@/components/pagetion/Pagetion.vue";//分页
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus'

const tableData = ref<TypeGroupPurchase[]>([])//接收表格数据
const backTop = ref()//回到顶部组件
const pagetio = reactive(new ClassPagination)//分页
const productData = ref([])//接收商品数据
const drawerSkuList = ref<TypeGroupSkuList[]>([])//抽屉sku列表数据
const hidePopover = ref(false)//批量定价气泡显示隐藏
const dialogVisible = ref(false)//skuList更新弹窗显示隐藏
const batchPrice = ref(1)//批量定价
const inde = ref(0)//sku当前行下标
const updateData = ref()//skuList更新弹窗数据
const updateGroupPrice = ref()//skuList更新弹窗价格
const drawer = ref(false)//抽屉是否显示
const tit = ref('')//抽屉title
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive(new ClassGroupEdit())//编辑添加传递的参数
const form = reactive({ ...ruleForm })

//活动状态
const adStatusMap = [
    { value: 0, name: '冻结' },
    { value: 1, name: '活动' },
]

//团购时间验证
const validateGmtEnd = (rule: object, value: number, callback: Function) => {
    if (ruleForm.gmtStart && ruleForm.gmtStart > value) {
        return callback(new Error('结束时间不能小于开始时间'))
    } else {
        callback()
    }
}

// 验证规则
const rules = reactive({
    gmtEnd: [//结束时间
        { validator: validateGmtEnd, trigger: 'change' },
    ],
})

// 初始化数据需要传递的参数
let params = reactive({
    _gp: "admin.groupshop",
    _mt: "list",
    id: undefined,
    spuName: "",
    status: undefined,
    page: pagetio.pageNo,
    limit: pagetio.pageSize
})

// 搜索需要的数据
let searchData = reactive({
    id: undefined,
    status: undefined,
    spuName: ""
})

// 初始化数据
function loadInit() {
    post(params).then(res => {
        console.log(res);
        let { data, errmsg, errno } = res
        if (200 == errno) {
            tableData.value = data.items
            pagetio.total = data.total
        } else {
            ElMessage.error(errmsg)
        }
    })
}
loadInit()

// 搜索
function handelSearch() {
    params.id = searchData.id
    params.status = searchData.status
    params.spuName = searchData.spuName
    loadInit()
}

// 添加
function handelAdd() {
    tit.value = '创建'
    Object.assign(ruleForm, form)
    drawerSkuList.value.length = 0
    drawer.value = true
}

// 编辑
function handelEdit(row: TypeGroupPurchase) {
    drawerSkuList.value.length = 0
    tit.value = '修改'
    Object.assign(ruleForm, { ...row, id: row.id })
    let skuList = JSON.parse(JSON.stringify(row.groupShopSkuDTOList))
    drawerSkuList.value.push(...skuList)
    drawer.value = true
}

// 批量定价
function handelGroupPrice() {
    if (drawerSkuList.value.some(val => val.price < batchPrice.value)) return ElMessage.warning('团购价不能高于现价')
    drawerSkuList.value.forEach((item: TypeGroupSkuList) => {
        item.skuGroupShopPrice = batchPrice.value
        return item
    });
    hidePopover.value = false
    batchPrice.value = 1
}

// skuList更新
function handelUpdate(index: number, row: TypeGroupSkuList) {
    inde.value = index
    updateData.value = row
    updateGroupPrice.value = row.skuGroupShopPrice
    dialogVisible.value = true
}

// skuList更新确定按钮
function confirmUpdate() {
    if (drawerSkuList.value[inde.value].price < updateGroupPrice.value) return ElMessage.warning('团购价不能高于现价')
    drawerSkuList.value[inde.value].skuGroupShopPrice = updateGroupPrice.value
    dialogVisible.value = false
}

// 编辑添加请求
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (ruleForm.spuId == 0) return ElMessage.warning('请选择团购商品')
            if (ruleForm.gmtStart == 0 || ruleForm.gmtEnd == 0) return ElMessage.warning('请选择团购时间')
            if (ruleForm.minNum == 0) return ElMessage.warning('请输入团购基础人数')
            if (drawerSkuList.value[inde.value].skuGroupShopPrice == undefined) return ElMessage.warning('请定义团购价格')
            let groupShopSkuList = JSON.stringify(drawerSkuList.value)
            ruleForm.groupShopSkuList = groupShopSkuList
            let data = reactive({
                _gp: 'admin.groupshop',
                _mt: tit.value == '创建' ? "create" : 'edit',
                ...ruleForm
            })
            post(data).then(res => {
                let { errmsg, errno } = res
                console.log(res);
                if (200 == errno) {
                    ElMessage.success(tit.value == '创建' ? '创建成功' : '修改成功')
                    drawer.value = false
                    loadInit()
                } else {
                    ElMessage.error(errmsg)
                }

            })
        } else {
            console.log('error submit!')
            return false
        }
    })
}

// 删除
function handelDelete(row: TypeGroupPurchase) {
    let delParams = reactive({
        _gp: 'admin.groupshop',
        _mt: 'delete',
        id: row.id
    })
    ElMessageBox.confirm(
        '是否删除此团购商品？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        post(delParams).then(res => {
            let { errno, errmsg } = res
            if (200 == errno) {
                ElMessage.success("删除成功")
                loadInit()
            } else {
                ElMessage.error(errmsg)
            }
        })
    })
}

// 获取抽屉sku列表数据
function loadDrawSkuList() {
    let data = {
        _gp: 'admin.product',
        _mt: 'detail',
        spuId: ruleForm.spuId
    }
    post(data).then(res => {
        console.log(res);
        let { data, errmsg, errno } = res
        if (200 == errno) {
            drawerSkuList.value = data.skuList
            data.skuList.forEach((item: { skuId: number, id: number }) => {
                item.skuId = item.id
            })
        } else {
            ElMessage.error(errmsg)
        }
    })
}

// 请求抽屉商品数据
function drawProduct() {
    let data = {
        _gp: 'admin.product',
        _mt: 'getSpuBigTree'
    }
    post(data).then(res => {
        let { data, errno, errmsg } = res
        if (200 == errno) {
            productData.value = data
        } else {
            ElMessage.error(errmsg)
        }
    })
}
drawProduct()

// 分页组件子传父自定义事件
const pageChange = (e: TypePage) => {
    params.page = e._pageNo
    params.limit = e._pageSize
    loadInit()
    nextTick(() => {
        backTop.value.$el.click?.()
    })
}
</script>

<style lang="less" scoped>
.el-form-item {
    margin-right: 10px !important;
}

.input {
    height: 40px !important;
}

.el-select {
    width: 200px;
}

.el-input {
    width: 200px;
}

/deep/ .el-drawer__header {
    border-bottom: 2px solid #f1f1f1;
    padding: 20px;
    margin-bottom: 0 !important;
}

.drawer_spu {
    border-bottom: 2px solid #f1f1f1;
    padding-left: 20px;

    .drawer_spu_item {
        padding-left: 35px;
    }
}

.drawer_sku {

    .drawer_sku_header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20px;
    }
}

/deep/ .el-drawer__body {
    padding: 0 !important;
}

.el-drawer__body,
.el-dialog__body {
    .el-form-item {
        margin-bottom: 20px !important;
    }
}

.popover_p {
    padding-left: 30px;
}

.el-dialog__body {
    .el-form {
        padding: 0 40px;
    }
}
</style>